<?php

namespace App\Http\Controllers\Auth;

use App\EloquentORM\User;
use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
	
	public function redirectToProvider()
	{
		return Socialite::driver('github')->redirect();
	}
	
	public function handleProviderCallback()
	{
		
		
		$github_user = Socialite::driver('github')->stateless()->user();
		
		try{
			$user=User::query()->where(['email'=>$github_user->email])->firstOrFail();
		}catch (\Exception $exception){
			$user=User::query()->create([
				'name'=>$github_user->nickname,
				'email'=>$github_user->email,
				'github_name'=>$github_user->nickname,
				'avatar'=>$github_user->avatar,
				'verified'=>1,
			]);
		}
		
		
		
		Auth::login($user,true);
		return Redirect()->guest('/');
	}
	
	public function redirectPath()
	{
		if (method_exists($this, 'redirectTo')) {
			return $this->redirectTo();
		}
		
		return property_exists($this, 'redirectTo') ? $this->redirectTo : '/';
	}
}
